/* 
    处理笔记的逻辑
*/
const { sqlQuery } = require("../mysql/index");
const { responseMsg } = require("../utils");

module.exports = {
  addNote,
  getNoteList,
};

// 获取笔记列表
async function getNoteList(labelId) {
  let sql = `select noteId,desc_str,code_str,labelId from note_data`;
  let extraSql = labelId
    ? ` where labelId=${labelId} order by noteId desc;`
    : " order by noteId desc;";

  return new Promise(function (resolve, reject) {
    sqlQuery(
      sql + extraSql,
      (data) => {
        const dataRes = data?.map((item) => {
          let result = { ...item, code: item.code_str, desc: item.desc_str };
          delete result.code_str;
          delete result.desc_str;
          return result;
        });
        resolve(responseMsg(dataRes, "success"));
      },
      (err) => {
        reject(responseMsg(err, "error"));
      }
    );
  });
}

// 添加笔记
async function addNote(data) {
  const { desc, code, labelId } = data;

  let sql = `insert into note_data(desc_str,code_str,labelId) values("${desc}","${code}","${labelId}");`;
  return new Promise(function (resolve, reject) {
    sqlQuery(
      sql,
      (data) => {
        resolve(responseMsg("ok", "success"));
      },
      (err) => {
        console.log("error:", err);
        reject(responseMsg(err, "error"));
      }
    );
  });
}
